package com.bhs.sansonglogistics.ui.login;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.LoginBean;
import com.bhs.sansonglogistics.net.Config;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.other.ConfigActivity;
import com.bhs.sansonglogistics.ui.other.WebViewActivity;
import com.bhs.sansonglogistics.utils.CountDownTimerUtils2;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 手机号登录
 */
public class PhoneNumberLoginActivity extends BaseActivity implements NetCallBack, TextWatcher, View.OnClickListener {

    private EditText mEtPhone;
    private EditText mEtCode;
    private Button mBtnLogin;
    private TextView mTvAgreement;
    private TextView mTvGetCode;
    private ImageView mIvAgreement;
    private boolean isCheck;

    @Override
    public int initLayout() {
        return R.layout.activity_phone_number_login;
    }

    @Override
    public void initView() {
        //有token直接去首页
        mEtPhone = findViewById(R.id.et_phone);
        mEtCode = findViewById(R.id.et_code);
        mBtnLogin = findViewById(R.id.btn_login);
        mTvAgreement = findViewById(R.id.tv_agreement);
        mTvGetCode = findViewById(R.id.tv_getCode);
        mEtCode.addTextChangedListener(this);
        mEtPhone.addTextChangedListener(this);
        mIvAgreement = findViewById(R.id.iv_agreement);
        findViewById(R.id.tv_title).setOnClickListener(this);
        LinearLayout mLlAgreement = findViewById(R.id.ll_agreement);
        mLlAgreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isCheck = !isCheck;
                if (isCheck) {
                    mIvAgreement.setImageResource(R.mipmap.ic_checked);
                } else {
                    mIvAgreement.setImageResource(R.mipmap.ic_unchecked);
                }
            }
        });
    }

    @Override
    public void initData() {
        String str = "我已阅读并同意《用户协议》、《隐私协议》";
        SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(str);
        // 在设置点击事件、同时设置字体颜色
        ClickableSpan clickableSpanOne = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, WebViewActivity.class)
                        .putExtra("url", Config.getUserProtocolUrl())
                        .putExtra("title", "用户协议"));
            }

            @Override
            public void updateDrawState(TextPaint paint) {
                paint.setColor(Color.parseColor("#485EF4"));
                // 设置下划线 true显示、false不显示
                paint.setUnderlineText(false);
            }
        };
        ClickableSpan clickableSpanTwo = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, WebViewActivity.class)
                        .putExtra("url", Config.getPrivacyPolicyUrl())
                        .putExtra("title", "隐私协议"));
            }

            @Override
            public void updateDrawState(TextPaint paint) {
                paint.setColor(Color.parseColor("#485EF4"));
                // 设置下划线 true显示、false不显示
                paint.setUnderlineText(false);
            }
        };

        spannableBuilder.setSpan(clickableSpanOne, 7, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableBuilder.setSpan(clickableSpanTwo, 14, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        mTvAgreement.setText(spannableBuilder);

        mTvGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(mEtPhone.getText().toString())) {
                    ToastUtil.show("请填写手机号");
                    return;
                }
                networkRequest(netApi.getCode("1", mEtPhone.getText().toString()), PhoneNumberLoginActivity.this);
            }
        });

        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isCheck) {
                    ToastUtil.show("请先同意隐私政策协议");
                    return;
                }
                login();
            }
        });
    }

    private void login() {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("login_type", "2");
        parameters.put("mobile", mEtPhone.getText().toString());
        parameters.put("platform", "logistics");
        parameters.put("verify_code", mEtCode.getText().toString());
        loadingPopupShow();
        networkRequest(netApi.login(parameters), this, 2);
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 2) {
            LoginBean loginBean = new Gson().fromJson(json, LoginBean.class);
            if (loginBean.isStatus()) {
                loadingPopup.dismissWith(new Runnable() {
                    @Override
                    public void run() {
                        MyUtils.login(mActivity, loginBean);
                    }
                });

            } else {
                ToastUtil.show(loginBean.getMsg());
                loadingPopupDismiss();
            }
        } else {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            if (bean.isStatus()) {
                CountDownTimerUtils2 countDownTimerUtils2 = new CountDownTimerUtils2(mTvGetCode, 60 * 1000, 1000);
                countDownTimerUtils2.start();
            } else {
                ToastUtil.show(bean.getMsg());
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }

    private void verify() {
        boolean verify = !TextUtils.isEmpty(mEtPhone.getText().toString()) && !TextUtils.isEmpty(mEtCode.getText().toString());
        mBtnLogin.setEnabled(verify);
        mBtnLogin.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    int count = 0;

    @Override
    public void onClick(View view) {
        if (mEtPhone.getText().toString().equals("000000")) {
            count++;
            if (count == 6) {
                count = 0;
                startActivity(new Intent(mActivity, ConfigActivity.class));
            }
        }
    }
}